package com.wanhugou.payment.util;


import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayFundTransToaccountTransferModel;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayFundTransOrderQueryRequest;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayFundTransOrderQueryResponse;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.wanhugou.payment.config.AliPayConfig;
import com.wanhugou.payment.config.SystemConfig;
import com.wanhugou.payment.domain.AliPay;
import com.wanhugou.payment.domain.AliTransfer;

@Component
public class AliPayUtils{
	
private static final Logger log = LoggerFactory.getLogger(AliPayUtils.class);
	
	@Autowired
	private AliPayConfig conf;
	
	@Autowired
	private SystemConfig sysConf;
	
	/**
	 * 
	 * <p>Description: 支付宝转账</br>
	 * @author zhangpf
	 * @param transfer
	 * @throws AlipayApiException
	 */
	public String aliTransfer(@RequestBody AliTransfer transfer) throws AlipayApiException {
		AlipayClient alipayClient = conf.getClient();
				
		AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
		AlipayFundTransToaccountTransferModel model = new AlipayFundTransToaccountTransferModel();
		model.setAmount(transfer.getAmount());
		model.setOutBizNo(transfer.getOut_biz_no());
		model.setRemark(transfer.getRemark());
		model.setPayeeType(transfer.getPayee_type());
		model.setPayeeAccount(transfer.getPayee_account());
		model.setPayerShowName(transfer.getPayer_show_name());
		model.setPayeeRealName(transfer.getPayee_real_name());
		request.setBizModel(model);
		AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
		if(response.isSuccess()){
			log.debug("<<<调用成功");
			return sysConf.getRes_success();
		} else {
			log.error("<<<调用失败");
			return sysConf.getRes_fail();
		}
	}
	
	public String query(String no) throws AlipayApiException{
		AlipayClient alipayClient = conf.getClient();
		AlipayFundTransOrderQueryRequest request = new AlipayFundTransOrderQueryRequest();
		AlipayFundTransToaccountTransferModel model = new AlipayFundTransToaccountTransferModel();
		model.setOutBizNo(no);
		request.setBizModel(model);
		AlipayFundTransOrderQueryResponse response = alipayClient.execute(request);
		if(response.isSuccess()){
			log.info("调用成功");
			return sysConf.getRes_success();
		} else {
			log.error("调用失败");
			return sysConf.getRes_fail();
		}
	}
	
	/**
	 * 
	 * <p>Description: 支付</br>
	 * @author zhangpf
	 * @param pay
	 * @return
	 * @throws IOException
	 */
	public String aliPay(AliPay pay) throws IOException{
		AlipayClient alipayClient = conf.getClient();
		//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setBody("我是测试数据");
		model.setSubject("App支付测试Java");
		model.setOutTradeNo(pay.getOut_trade_no());
		model.setTimeoutExpress("1m");
		model.setTotalAmount(pay.getTotal_amount());
		model.setProductCode("QUICK_MSECURITY_PAY");
		request.setBizModel(model);
//		request.setNotifyUrl("http://wanhutong.tunnel.qydev.com/payment/alipay/notify");
		request.setNotifyUrl("http://d9hvby.natappfree.cc/payment/alipay/notify");
		try {
	        //这里和普通的接口调用不同，使用的是sdkExecute
	        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
	       return response.getBody();
	    } catch (AlipayApiException e) {
	        e.printStackTrace();
	        return sysConf.getRes_fail();
		}
	}
	
	/**
	 * 支付宝异步请求通知
	 *
	 * @param request
	 * @return
	 * @throws AlipayApiException 
	 */
	public String notify(HttpServletRequest request) throws AlipayApiException {
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
		    String name = (String) iter.next();
		    String[] values = (String[]) requestParams.get(name);
		    String valueStr = "";
		    for (int i = 0; i < values.length; i++) {
		        valueStr = (i == values.length - 1) ? valueStr + values[i]
		                    : valueStr + values[i] + ",";
		  	}
		    //乱码解决，这段代码在出现乱码时使用。
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		//切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
		//boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
		boolean flag = AlipaySignature.rsaCheckV1(params, conf.getAli_public_key(), conf.getCharset(), "RSA2");
	    if(flag){
	    	log.debug("<<<回调成功");
	    	return sysConf.getRes_success();
	    }else{
	    	log.error("<<<回调失败");
	    	return sysConf.getRes_fail();
		}
	}
}
